#include "../include/config.h"
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <cjson/cJSON.h>
#include <string.h>

int load_config(const char *filename,config_t *cfg,mysql_config_t *mysql_cfg){
    int fd=open(filename,O_RDONLY);
    struct stat st;
    if(fstat(fd,&st)<0){
        perror("fstat");
        close(fd);
        return -1;
    }

    size_t size=st.st_size;
    char *buf=(char *)malloc(size+1);
    if(!buf){
        perror("malloc");
        close(fd);
        return -1;
    }

    ssize_t read_len = read(fd,buf,size);
    if(read_len<0){
        perror("read");
        free(buf);
        close(fd);
        return -1;
    }
    buf[read_len]='\0';
    close(fd);

    cJSON *json=cJSON_Parse(buf);
    free(buf);
    if(!json){
        fprintf(stderr,"JSON parse error:%s\n",cJSON_GetErrorPtr());
        return -1;
    }

    cJSON *ip=cJSON_GetObjectItemCaseSensitive(json,"ip");
    cJSON *port=cJSON_GetObjectItemCaseSensitive(json,"port");
    cJSON *default_upload_server=cJSON_GetObjectItemCaseSensitive(json,"default_upload_server");
    cJSON *secret=cJSON_GetObjectItemCaseSensitive(json,"secret");

    cJSON *mysql_user=cJSON_GetObjectItemCaseSensitive(json,"mysql_user");
    cJSON *mysql_passwd=cJSON_GetObjectItemCaseSensitive(json,"mysql_passwd");
    cJSON *mysql_db=cJSON_GetObjectItemCaseSensitive(json,"mysql_db");
    cJSON *mysql_host=cJSON_GetObjectItemCaseSensitive(json,"mysql_host");
    cJSON *mysql_port=cJSON_GetObjectItemCaseSensitive(json,"mysql_port");

    if(!cJSON_IsString(ip) || !cJSON_IsNumber(port)|| !cJSON_IsString(default_upload_server)||
       !cJSON_IsString(mysql_user) || !cJSON_IsString(mysql_passwd)||!cJSON_IsString(mysql_db)||
       !cJSON_IsString(mysql_host) || !cJSON_IsNumber(mysql_port)){
        fprintf(stderr,"Missing or invalid required fields in JSON\n");
        cJSON_Delete(json);
        return -1;
    }
    strncpy(cfg->ip,ip->valuestring,sizeof(cfg->ip)-1);
    cfg->port=port->valueint;
    strncpy(cfg->default_upload_server,default_upload_server->valuestring,sizeof(cfg->default_upload_server)-1);
    strncpy(cfg->secret,secret->valuestring,sizeof(cfg->secret)-1);

    strncpy(mysql_cfg->user,mysql_user->valuestring,sizeof(mysql_cfg->user)-1);
    strncpy(mysql_cfg->passwd,mysql_passwd->valuestring,sizeof(mysql_cfg->passwd)-1);
    strncpy(mysql_cfg->db,mysql_db->valuestring,sizeof(mysql_cfg->db)-1);
    strncpy(mysql_cfg->host,mysql_host->valuestring,sizeof(mysql_cfg->host)-1);
    mysql_cfg->port=mysql_port->valueint;

    cJSON_Delete(json);
    return 0;
}
